package com.hjm.friend.manage;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hjm.common.core.constants.CacheConstants;
import com.hjm.common.core.enums.ResultCode;
import com.hjm.friend.domain.question.Question;
import com.hjm.friend.mapper.question.QuestionMapper;
import com.hjm.redis.service.RedisService;
import com.hjm.security.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class QuestionCacheManager {

    @Autowired
    private RedisService redisService;

    @Autowired
    QuestionMapper questionMapper;

    // 获取 exam 的长度
    public Long getListSize(){
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }


    public void refreshCache() {
        // 从数据库中 进行获取
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId).orderByDesc(Question::getCreateTime));

        if(CollectionUtil.isEmpty(questionList)){
            return ;
        }

        // 将 id 按顺序 进行插入 redis 的链表中
        List<Long> questionIdlist = questionList.stream().map(Question::getQuestionId).toList();

        redisService.deleteObject(CacheConstants.QUESTION_LIST);
        redisService.rightPushAll(CacheConstants.QUESTION_LIST,questionIdlist);
    }

    public Long preQuestion(Long questionId) {
        // 从 题目列表中 获取 下标
        Long index = redisService.indexOfForListValue(CacheConstants.QUESTION_LIST, questionId);
        if(index == 0){
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForListValue(CacheConstants.QUESTION_LIST,index-1,Long.class);
    }

    public Long nextQuestion(Long questionId) {
        Long listSize = redisService.getListSize(CacheConstants.QUESTION_LIST);
        // 从 题目列表中 获取 下标
        Long index = redisService.indexOfForListValue(CacheConstants.QUESTION_LIST, questionId);
        if(index == listSize-1 ){
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForListValue(CacheConstants.QUESTION_LIST,index+1,Long.class);
    }
}

